<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>UselessCapsLock 配置</title>
    <style>
        :root {
            --background: #e0e5ec;
            --text-color: #4d4d4d;
            --shadow-light: #ffffff;
            --shadow-dark: #a3b1c6;
            --accent: #6d5dfc;
            --accent-light: #8f85fb;
        }

        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: var(--background);
            color: var(--text-color);
        }

        .container {
            background-color: var(--background);
            padding: 20px;
            border-radius: 20px;
            box-shadow: 8px 8px 16px var(--shadow-dark),
                       -8px -8px 16px var(--shadow-light);
            position: relative;
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: var(--text-color);
            margin-right: 150px;
        }

        .mapping-row {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
            padding: 15px;
            border-radius: 15px;
            box-shadow: inset 4px 4px 8px var(--shadow-dark),
                       inset -4px -4px 8px var(--shadow-light);
        }

        select {
            padding: 10px 15px;
            border-radius: 12px;
            border: none;
            background-color: var(--background);
            color: var(--text-color);
            box-shadow: 4px 4px 8px var(--shadow-dark),
                       -4px -4px 8px var(--shadow-light);
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 150px;
        }

        select:focus {
            outline: none;
            box-shadow: inset 4px 4px 8px var(--shadow-dark),
                       inset -4px -4px 8px var(--shadow-light);
        }

        button {
            padding: 12px 24px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            background: var(--background);
            color: var(--text-color);
            box-shadow: 4px 4px 8px var(--shadow-dark),
                       -4px -4px 8px var(--shadow-light);
            transition: all 0.3s ease;
            font-weight: bold;
        }

        button:active {
            box-shadow: inset 4px 4px 8px var(--shadow-dark),
                       inset -4px -4px 8px var(--shadow-light);
        }

        button.primary {
            background: var(--accent);
            color: white;
        }

        button.primary:hover {
            background: var(--accent-light);
        }

        button.delete {
            padding: 8px 16px;
            color: #f44336;
        }

        .arrow {
            font-size: 24px;
            color: var(--text-color);
            margin: 0 10px;
        }

        .actions {
            margin-top: 20px;
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        .status-indicator {
            position: absolute;
            top: 25px;
            right: 20px;
            padding: 8px;
            border-radius: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            background: var(--background);
            box-shadow: 4px 4px 8px var(--shadow-dark),
                       -4px -4px 8px var(--shadow-light);
        }

        .status-group {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 0 12px;
            border-right: 2px solid var(--shadow-dark);
        }

        .settings-button {
            padding: 8px;
            margin-left: 4px;
            border: none;
            background: none;
            cursor: pointer;
            color: var(--text-color);
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.3s ease;
        }

        .settings-button:hover {
            transform: rotate(45deg);
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #f44336;
            transition: background-color 0.3s ease;
        }

        .status-dot.connected {
            background-color: #4CAF50;
        }

        .disconnected-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 2000;
        }

        .disconnected-message {
            background: var(--background);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 8px 8px 16px var(--shadow-dark),
                       -8px -8px 16px var(--shadow-light);
        }

        .settings-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1500;
        }

        .settings-panel {
            background: var(--background);
            padding: 30px;
            border-radius: 20px;
            box-shadow: 8px 8px 16px var(--shadow-dark),
                       -8px -8px 16px var(--shadow-light);
            min-width: 300px;
        }

        .setting-item {
            display: flex;
            align-items: center;
            gap: 15px;
            margin: 20px 0;
        }

        /* 开关样式 */
        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--shadow-dark);
            transition: .4s;
            border-radius: 34px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: var(--accent);
        }

        input:checked + .slider:before {
            transform: translateX(26px);
        }
    </style>
</head>
<body>
    <div class="disconnected-overlay">
        <div class="disconnected-message">
            <h2>连接已断开</h2>
            <p>程序可能已经关闭，请检查程序是否正在运行。</p>
            <button onclick="window.location.reload()">重新连接</button>
        </div>
    </div>
    
    <div class="container">
        <div class="status-indicator">
            <div class="status-group">
                <div class="status-dot"></div>
                <span>服务状态</span>
            </div>
            <button class="settings-button" onclick="toggleSettings()" title="设置">⚙️</button>
        </div>
        <h1>按键映射配置</h1>
        <div id="mappings"></div>
        <div class="actions">
            <button onclick="addMapping()">+ 添加映射</button>
            <button class="primary" onclick="saveConfig()">✓ 保存配置</button>
        </div>
    </div>

    <div class="settings-overlay" style="display: none;">
        <div class="settings-panel">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="margin: 0;">设置</h2>
                <button class="close-button" onclick="closeSettings()" style="background: none; box-shadow: none;">✕</button>
            </div>
            <div class="setting-item">
                <label class="switch">
                    <input type="checkbox" id="autoStartCheckbox">
                    <span class="slider"></span>
                </label>
                <span>开机自启动</span>
            </div>
            <div class="setting-item">
                <label class="switch">
                    <input type="checkbox" id="autoOpenConfigCheckbox">
                    <span class="slider"></span>
                </label>
                <span>启动时自动打开配置界面</span>
            </div>
        </div>
    </div>

    <script>
        const keyOptions = [
            "CapsLock",
            "LCtrl", "RCtrl",
            "LAlt", "RAlt",
            "LShift", "RShift",
            "LWin", "RWin",
            "Tab", "Esc", "Space", "Enter", "Backspace",
            "Insert", "Delete", "Home", "End", "PgUp", "PgDn",
            "F1", "F2", "F3", "F4", "F5", "F6",
            "F7", "F8", "F9", "F10", "F11", "F12"
        ];

        function createSelect() {
            const select = document.createElement('select');
            select.innerHTML = '<option value="">选择按键</option>' +
                keyOptions.map(key => `<option value="${key}">${key}</option>`).join('');
            return select;
        }

        function addMapping(sourceKey = '', destKey = '') {
            const mappingsDiv = document.getElementById('mappings');
            const row = document.createElement('div');
            row.className = 'mapping-row';

            const sourceSelect = createSelect();
            const destSelect = createSelect();
            sourceSelect.value = sourceKey;
            destSelect.value = destKey;

            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'delete';
            deleteBtn.textContent = '删除';
            deleteBtn.onclick = () => row.remove();

            row.appendChild(sourceSelect);
            const arrow = document.createElement('span');
            arrow.className = 'arrow';
            arrow.textContent = '→';
            row.appendChild(arrow);
            row.appendChild(destSelect);
            row.appendChild(deleteBtn);

            mappingsDiv.appendChild(row);
        }

        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();
                document.getElementById('mappings').innerHTML = '';
                config.mappings.forEach(mapping => {
                    addMapping(mapping.source_key, mapping.destination_key);
                });
            } catch (error) {
                console.error('加载配置失败:', error);
                alert('加载配置失败');
            }
        }

        async function saveConfig() {
            const mappings = [];
            document.querySelectorAll('.mapping-row').forEach(row => {
                const selects = row.querySelectorAll('select');
                const source = selects[0];
                const dest = selects[1];
                if (source.value && dest.value) {
                    mappings.push({
                        source_key: source.value,
                        destination_key: dest.value
                    });
                }
            });

            if (mappings.length === 0) {
                showToast('请至少添加一个按键映射', true);
                return;
            }

            try {
                const response = await fetch('/api/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ mappings })
                });

                if (response.ok) {
                    showToast('配置已保存');
                } else {
                    const error = await response.text();
                    throw new Error(error || '保存失败');
                }
            } catch (error) {
                console.error('保存配置失败:', error);
                showToast('保存失败: ' + error.message, true);
            }
        }

        function showToast(message, isError = false) {
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                bottom: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: ${isError ? '#f44336' : 'var(--accent)'};
                color: white;
                padding: 12px 24px;
                border-radius: 12px;
                box-shadow: 4px 4px 8px var(--shadow-dark);
                opacity: 0;
                transition: opacity 0.3s ease;
                z-index: 1000;
            `;
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => toast.style.opacity = '1', 10);
            setTimeout(() => toast.style.opacity = '0', 2000);
            setTimeout(() => document.body.removeChild(toast), 2300);
        }

        let ws;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 3;
        
        function connectWebSocket() {
            ws = new WebSocket(`ws://${window.location.host}/ws`);
            
            ws.onopen = () => {
                document.querySelector('.status-dot').classList.add('connected');
                document.querySelector('.disconnected-overlay').style.display = 'none';
                reconnectAttempts = 0;
                getAutoStartStatus();
            };
            
            ws.onclose = () => {
                document.querySelector('.status-dot').classList.remove('connected');
                if (reconnectAttempts < maxReconnectAttempts) {
                    reconnectAttempts++;
                    setTimeout(connectWebSocket, 1000 * reconnectAttempts);
                } else {
                    document.querySelector('.disconnected-overlay').style.display = 'flex';
                }
            };
            
            ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
            };
            
            ws.onmessage = (event) => {
                const message = JSON.parse(event.data);
                if (!message.success) {
                    showToast(message.error, true);
                    return;
                }

                switch (message.type) {
                    case 'autoStartStatus':
                        document.getElementById('autoStartCheckbox').checked = message.data;
                        break;
                    case 'settings':
                        document.getElementById('autoOpenConfigCheckbox').checked = 
                            message.data.auto_open_config;
                        break;
                }
            };
        }

        function toggleSettings() {
            document.querySelector('.settings-overlay').style.display = 'flex';
            getAutoStartStatus();
        }

        function closeSettings() {
            document.querySelector('.settings-overlay').style.display = 'none';
        }

        function getAutoStartStatus() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 'getAutoStart'
                }));
                ws.send(JSON.stringify({
                    type: 'getSettings'
                }));
            }
        }

        // 添加自启动切换事件
        document.getElementById('autoStartCheckbox').addEventListener('change', function(e) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 'setAutoStart',
                    data: e.target.checked
                }));
            }
        });

        // 添加自动打开配置切换事件
        document.getElementById('autoOpenConfigCheckbox').addEventListener('change', function(e) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 'setSettings',
                    data: {
                        auto_open_config: e.target.checked
                    }
                }));
            }
        });

        // 页面加载时加载配置
        loadConfig();
        connectWebSocket();
    </script>
</body>
</html> 